package com.todod.service.impl;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.IpAddr;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.common.util.UserAgentUtil;
import com.todod.entity.QueryEntry;
import com.todod.mapper.LoginLogMapper;
import com.todod.model.LoginLog;
import com.todod.model.User;
import com.todod.service.ILoginLogService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsh
 * @since 2020-10-14
 */
@Service
@Transactional
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements ILoginLogService {

	public IPage<LoginLog> getPage(QueryEntry queryEntry) {
		Page<LoginLog> page = new Page<LoginLog>(queryEntry.getPage(), queryEntry.getLimit());

		QueryWrapper<LoginLog> queryWrapper = new QueryWrapper<LoginLog>();

		if (!StringUtils.isBlank(queryEntry.getLoginName())) {
			queryWrapper.like("sl_login_name", "%" + queryEntry.getLoginName() + "%");
		}

		if (!StringUtils.isBlank(queryEntry.getBeginDate())) {
			queryWrapper.ge("sl_create_time", queryEntry.getBeginDate());
		}
		if (!StringUtils.isBlank(queryEntry.getEndDate())) {
			queryWrapper.le("sl_create_time", queryEntry.getEndDate() + " 23:59:59");
		}

		queryWrapper.orderByDesc("sl_create_time");
		IPage<LoginLog> ipage = this.page(page, queryWrapper);

		return ipage;

	}

	/**
	 * 另一线程， 保存
	 * 
	 * @Title: savaData
	 * @Description:
	 * @author gsh
	 * @date 2020年4月12日
	 * @param userId
	 * @param browser
	 * @param ipAddr
	 * @param loginName
	 * @param loginType
	 */
	@Override
	public void add(User u, HttpServletRequest res, String loginName, String loginType) {
		String browser = UserAgentUtil.getBrowser(res);
		String ipAddr = IpAddr.getIpAddr(res);

		Thread thread = new Thread() {
			@Override
			public void run() {
				savaData(u, browser, ipAddr, loginName, loginType);
			}
		};
		thread.start();
	}

	public void savaData(User u, String browser, String ipAddr, String loginName, String loginType) {

		LoginLog loginLog = new LoginLog();
		loginLog.setId(SnowflakeIdGenerator.getId());
		loginLog.setCreateTime(new Date());

		loginLog.setBrowser(browser);
		loginLog.setIpAddr(ipAddr);
		loginLog.setLoginName(loginName);
		loginLog.setLoginType(loginType);

		if (u != null) {
			if (!"1".equals(u.getState())) {
				loginLog.setLoginSuc("2"); // 登陆失败
			} else {
				loginLog.setCreateUserId(u.getId());
				loginLog.setUserId(u.getId());
				loginLog.setLoginSuc("1"); // 登陆成功
			}

		} else {
			loginLog.setLoginSuc("2"); // 登陆失败
		}

		save(loginLog);
	}

}
